#!/usr/bin/python

# Copyright (c) 2010 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3 as published
# by the # Free Software Foundation
#
# lp-mark-bugs-released is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.

'''Mark bugs that are Fix Committed on a release to be Fix Released'''

import datetime
import os
import sys
import tempfile

from launchpadlib.launchpad import Launchpad
from launchpadlib.errors import HTTPError

opt_dry_run = False

def mark_released (bug):
    if bug.status == 'Fix Committed':
        print "Marking bug " + str(bug.bug.id) + " as 'Fix Released'"
        bug.status = "Fix Released"
        if not opt_dry_run:
            bug.lp_save()

def main():
    if len(sys.argv) != 3:
        print >> sys.stderr, '''Mark bugs 'Fix Committed' on a release as released

    Usage: %s <project name> <version>''' % sys.argv[0]
        sys.exit(1)

    (project, version) = sys.argv[1:]

    try:
        launchpad = Launchpad.login_with('ubuntu-dev-tools', 'production')
    except Exception, error:
        print >> sys.stderr, 'Could not connect to Launchpad:', str(error)
        sys.exit(2)

    try:
        # Look up the project using the Launchpad instance.
        proj = launchpad.projects[project]
        # Find the release in the project's releases collection.
        release = None
        for rel in proj.releases:
            if rel.version == version:
                release = rel
                break
        if not release:
            print >> sys.stderr, '''Unable to find release: %s''' % version
            sys.exit(1)

        # Mark any fix committed bugs released
        for task in release.milestone.searchTasks(status="Fix Committed"):
            if task.milestone is None:
                for othertask in task.related_tasks:
                    if othertask.milestone.name == release.milestone.name:
                        mark_released(othertask)
            else:
                mark_released(task)

    except HTTPError, error:
        print 'An error happened in the upload: %s\n%s' %(
            error.content,
            error.__dict__)
        sys.exit(1)

if __name__ == '__main__':
    main()
